package com.frxuexi.user.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.lib_base.room.AskLeave
import com.frxuexi.user.repository.UserRepository

class MyDataSource(userRepository: UserRepository):PagingSource<Int,AskLeave>() {
    val userRepository=userRepository
    override fun getRefreshKey(state: PagingState<Int, AskLeave>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, AskLeave> {
        return try {
            var currentPage=params.key?:1
            var size=10
            val leaves = userRepository.selectByPage(currentPage, size)
            val count=userRepository.getCount()/size+1
            val nextPage=if(currentPage<count){
                currentPage+1
            }else{
                null
            }

            LoadResult.Page(data = leaves, prevKey = null, nextKey = nextPage)
        }catch (e:Exception){
            LoadResult.Error(e)
        }
    }
}